package cn.oms.auth.service.service;

import cn.tedu.knows.commons.model.Permission;
import cn.tedu.knows.commons.model.Role;
import cn.tedu.knows.commons.model.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private RestTemplate restTemplate;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String url="http://sys-service/v1/auth/user?username={1}";
        User user=restTemplate.getForObject(url,User.class,username);
        if(user==null){
            throw new  UsernameNotFoundException("用户名不存在");
        }
        url="http://sys-service/v1/auth/permissions?id={1}";
        //当控制器方法返回List类型时
        // 我们使用List指定泛型的类型数组来接收
        Permission[] permissions=restTemplate.getForObject(
                        url , Permission[].class , user.getId());
        url="http://sys-service/v1/auth/roles?id={1}";
        Role[] roles=restTemplate.getForObject(
                        url , Role[].class       , user.getId());
        //定义auth数组,包含所有角色和权限的名称
        String[] auth=new String[permissions.length+roles.length];
        int i=0;
        for(Permission p: permissions){
            auth[i++]=p.getName();
        }
        for(Role r: roles){
            auth[i++]=r.getName();
        }
        //构建UserDetails对象
        UserDetails u= org.springframework.security.core.userdetails
                .User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(auth)
                .accountLocked(user.getLocked()==1)
                .disabled(user.getEnabled()==0)
                .build();
        // 千万不要忘记返回u
        return u;

    }
}

